using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace Dolls
{
	public class UiLongTimer : MonoBehaviour
	{
		public string targetTimeStr;
		public Text   textComponent;

		private DateTime? TargetTime { get; set; }

		public event Action<UiLongTimer> FinishedEventHandle;

		public void StartCountdown(DateTime? time)
		{
			TargetTime = time;
			if (TargetTime == null || textComponent == null)
				throw new Exception("错误：倒计时参数不完整");
			StartCoroutine(Countdown());
		}

		public void StopCountdown()
		{
			StopAllCoroutines();
			TargetTime = null;
		}

		private IEnumerator Countdown()
		{
			while (true)
			{
				var now = DateTime.Now;
				if (TargetTime < now)
					break;
				var span = TargetTime - now;
				textComponent.text = TimeToString(span);
				yield return new WaitForSeconds(1);
			}
			textComponent.text = TimeToString(null);
			FinishedEventHandle?.Invoke(this);
		}

		private static string TimeToString(TimeSpan? span)
		{
			return span.HasValue
				? $"{Math.Floor(span.Value.TotalHours)}:{span.Value.Minutes:00}:{span.Value.Seconds:00}"
				: "00:00:00";
		}
	}
}